import os
import subprocess

def merge_segments(task_info, save_dir, log_callback):
    """合并所有TS片段为单个文件（使用FFmpeg）"""
    log_callback("开始合并文件 (FFmpeg)...")
    
    # 最终视频路径
    output_file = os.path.join(
        save_dir,
        f"{task_info['name']}.mp4"
    )
    
    # 创建合并列表文件
    list_file = os.path.join(save_dir, "file_list.txt")
    with open(list_file, 'w', encoding='utf-8') as f:
        for i in range(task_info['totalNum']):
            ts_file = os.path.join(save_dir, f"{task_info['uid']}_{i}.ts")
            f.write(f"file '{ts_file}'\n")
    
    # 使用FFmpeg合并
    try:
        ffmpeg_cmd = [
            'ffmpeg',
            '-f', 'concat',
            '-safe', '0',
            '-i', list_file,
            '-c', 'copy',
            '-y',
            output_file
        ]
        
        result = subprocess.run(
            ffmpeg_cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding='utf-8'
        )
        
        if result.returncode == 0:
            log_callback(f"合并成功: {output_file}")
        else:
            log_callback(f"合并失败: {result.stdout}")
        
    except Exception as e:
        log_callback(f"合并过程中出错: {str(e)}")
    finally:
        # 清理临时文件
        try:
            os.remove(list_file)
            for i in range(task_info['totalNum']):
                ts_file = os.path.join(save_dir, f"{task_info['uid']}_{i}.ts")
                os.remove(ts_file)
        except:
            pass